<template>
  <view class="viewport">
    <!-- #ifndef MP-TOUTIAO -->
    <!-- 自定义导航栏 -->
    <uni-nav-bar class="uni-nav-bar" background-color="rgba(255,255,255,0)" :border="false" :statusBar="true"
      @clickLeft="goBack">
      <template #left>
        <view class="icon-arrow-left"></view>
      </template>
      <template #default>
        <view class="title">考点练习</view>
      </template>
    </uni-nav-bar>
    <!-- #endif -->
    <!-- 抖音小程序顶部导航 -->
    <!-- #ifdef MP-TOUTIAO -->
    <view class="toutiao-nav-bar">
      <view class="status-bar"></view>
      <view class="title-container">
        <view class="title">考点练习</view>
      </view>
    </view>
    <!-- #endif -->
    <scroll-view class="scroll-view" enable-back-to-top scroll-y>
      <view class="exercise-progress">
        <view class="progress-title">学习进度</view>
        <view class="progress-container">
          <view class="progress-overview">
            <view class="overview-items">
              <view class="item" @tap="toKnowExerciseProgress(1)">
                <view class="num">{{ knowExerciseProgressOverView.noExerciseCount }}</view>
                <view class="desc">未练习</view>
              </view>
              <view class="item" @tap="toKnowExerciseProgress(2)">
                <view class="num">{{ knowExerciseProgressOverView.noSkilledCount }}</view>
                <view class="desc">未熟练掌握</view>
              </view>
              <view class="item" @tap="toKnowExerciseProgress(3)">
                <view class="num">{{ knowExerciseProgressOverView.skilledCount }}</view>
                <view class="desc">已掌握</view>
              </view>
            </view>
            <view class="overview-tips" v-if="preKnowExercise">
              <view class="tips">
                <text class="tag">上次</text>
                {{ preKnowExercise.name }}
              </view>
              <view class="btn" @tap="continueExercise(preKnowExercise?.knowTypeCode!, preKnowExercise?.id!)">继续练习
              </view>
            </view>
          </view>
        </view>
      </view>
      <uv-sticky :custom-nav-height="-12">
        <view class="exercise-progress-header">
          <!--可通过设置bar-animate-mode="worm"开启毛毛虫模式  -->
          <uv-tabs :list="knowExerciseGroupLabels" :current="swiperCurrent" lineWidth="20" lineColor="#5cbc85"
            :activeStyle="{
              color: '#303133',
              fontSize: '34rpx',
              fontWeight: 'bold',
              transform: 'scale(1.05)'
            }" :inactiveStyle="{
              color: '#2f2f2f',
              transform: 'scale(1)'
            }" itemStyle="padding-left: 15px; padding-right: 15px; height: 50px;" @change="tabsChange"></uv-tabs>
        </view>
      </uv-sticky>
      <swiper class="swiper-container " :current="swiperCurrent" @change="swiperChange">
        <swiper-item v-for="(item, index) in knowExerciseGroupLabels" :key="index">
          <view class="know-type-item" v-if="knowExerciseGroupList[index].length > 0"
            v-for="(knowTypeItem, knowTypeIndex) in knowExerciseGroupList[index]" :key="knowTypeIndex">
            <view class="know-type-item-header" @tap="openKnowExerciseGroup(knowTypeItem.code!)">
              <view class="know-type-item-label">
                <view class="icon icon-circle-down" :class="knowTypeItem.status"></view>
                <view class="name">{{ knowTypeItem.name }}</view>
              </view>
              <view class="know-type-item-num">
                {{ knowTypeItem.knows?.length }}个
              </view>
            </view>
            <view class="know-item-content">
              <view class="know-item" :class="knowTypeItem.status" v-for="(knowItem, knowIndex) in knowTypeItem.knows"
                :key="knowIndex" v-if="knowTypeItem.status === 'open'"
                @tap="toKnowExercise(knowTypeItem.code!, knowItem.id!)">
                <view class="left">
                  <view class="title">{{ knowItem.name }}</view>
                  <view class="tips">
                    <text class="txt">共{{ knowItem.questions?.length }}题</text>
                    <text class="txt">未做题<text class="num">{{ knowItem.questions!.length -
                      knowItem.questionAnswerCount
                        }}</text> </text>
                    <text class="txt">对题<text class="num">{{ knowItem.questionAnswerCorrectCount }}</text> </text>
                    <text class="txt">正确率<text class="num">{{ knowItem.answerCorrectRate }}%</text> </text>

                  </view>
                </view>
                <view class="right"> <uni-icons class="right" type="right" color="#4a4a4a" size="20"></uni-icons>
                </view>
              </view>

            </view>

          </view>
          <view class="know-type-empty" v-else>
            <image class="img" src="https://media.jiabl.net.cn/miniapp/images/empty.png" mode="widthFix" />
            <view class="txt">您暂无{{ index == 1 ? '未练习' : index == 2 ? '未熟练掌握' : '已掌握' }}的考点，继续加油～</view>
          </view>
        </swiper-item>
      </swiper>
    </scroll-view>

  </view>
</template>

<script lang="ts" setup>
  import { onLoad, onShow } from '@dcloudio/uni-app'
  import { ref, reactive, computed } from 'vue'
  import type { KnowExercise, Know } from '@/api/base/types'
  import type { KnowExerciseProgress } from '@/api/exam/types'

  import { ExerciseTypeEnum } from '@/api/constants'
  import { useExericseStore } from '@/stores/modules/exercise_store'

  import { useGetKnowExercises, useKnowExerciseProgressOver, useGetKnowExerciseProgress } from '@/composables/Exercise'

  import uvTabs from '@climblee/uv-ui/components/uv-tabs/uv-tabs.vue'
  import uvSticky from '@climblee/uv-ui/components/uv-sticky/uv-sticky.vue'

  const exericseStore = useExericseStore()

  // #ifdef MP
  let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  // #endif
  // #ifdef MP-TOUTIAO
  // 获取小程序下胶囊按钮的布局位置信息
  // 上边界坐标，单位：px
  let top = (menuButtonInfo.top - 10) + 'px'
  const statusBarHeight = ref(top)
  // 高度，单位：px
  let height = (menuButtonInfo.height + 20) + 'px'
  const titleHeight = ref(height)
  // #endif
  const baseType = ref<string>()
  // 考点练习进度标签
  const knowExerciseGroupLabels = reactive([
    {
      name: '全部',
      code: 0
    },
    {
      name: '未练习',
      code: 1
    },
    {
      name: '未熟练掌握',
      code: 2
    },
    {
      name: '已掌握',
      code: 3
    },
  ])

  // 考点练习列表
  const knowExercises = ref<KnowExercise[]>([])
  // 上传练习的考点
  const preKnowExercise = ref<Know>()

  onLoad((options: any) => {
    baseType.value = options.baseType
    knowExercises.value = useGetKnowExercises(baseType.value!) || []
  })

  onShow(() => {
    // 上一次练习的考点
    let preKnowExerciseExcercise = exericseStore.getKnowExerciseIndex(baseType.value!)
    if (preKnowExerciseExcercise) {
      preKnowExercise.value = knowExercises.value.find(item => item.code == preKnowExerciseExcercise.knowTypeCode)?.knows?.find(item => item.id == preKnowExerciseExcercise.knowId)
    }
    // 加载考点练习分组列表列表
    loadKnowExerciseGroupList()

  })

  /**
 * KnowExerciseGroup，考点练习分组对象
 */
  export interface KnowExerciseGroup {
    /**
     * 题库类型
     */
    baseTypeCode?: string;
    /**
     * 代码
     */
    code?: string;

    /**
     * 名称
     */
    name?: string;
    /**
     * 状态
     */
    status: string;
    /**
     * 考点练习进度
     */
    knows: KnowExerciseProgress[]
  }

  //考点练习分组列表
  const knowExerciseGroupList = ref<KnowExerciseGroup[][]>([])

  // 加载考点练习分组列表列表
  const loadKnowExerciseGroupList = () => {
    knowExerciseGroupLabels.forEach((knowProgressType, index: number) => {
      let list = filterKnowExerciseGroupList(knowProgressType.code)
      if (!knowExerciseGroupList.value[index]) {
        knowExerciseGroupList.value.push(list)
      }
      else {
        let openKnowExerciseGroupIndex = knowExerciseGroupList.value[index].findIndex(item => item.status === 'open')
        if (openKnowExerciseGroupIndex != -1) {
          let openListItem = list[openKnowExerciseGroupIndex]
          if (openListItem) {
            openListItem!.status = 'open'
          }
        }
        knowExerciseGroupList.value[index] = list
      }
    })
  }
  /**
   *考点类型是否有值
   * @param knowTypeCode
   * @param skilled
   */
  const filterKnowExerciseGroupList = (skilled: number) => {
    let knowExerciseGroup: KnowExerciseGroup[] = []
    knowExercises.value.forEach((item: KnowExercise) => {
      let knowExerciseProgress = getKnowExerciseProgress(item.code!, skilled)
      if (knowExerciseProgress.length >= 1) {
        knowExerciseGroup.push({ baseTypeCode: item.baseTypeCode, code: item.code, name: item.name, knows: knowExerciseProgress, status: 'close' })
      }
    })

    return knowExerciseGroup
  }
  /**
   * 获取考点进度
   */
  const getKnowExerciseProgress = (knowTypeCode: string, skilled: number) => {
    let list = useGetKnowExerciseProgress(baseType.value!, knowTypeCode)
    switch (skilled) {
      case 1:
        list = list.filter(item => item.skilled == 0)
        break
      case 2:
        list = list.filter(item => item.skilled == 1)
        break
      case 3:
        list = list.filter(item => item.skilled == 2)
        break
    }
    return list
  }

  const swiperCurrent = ref(0)
  // tabs通知swiper切换
  const tabsChange = (item: any) => {
    swiperCurrent.value = item.index
  }

  // swiperChange
  const swiperChange = (e: UniHelper.SwiperOnChangeEvent) => {
    swiperCurrent.value = e.detail.current
  }
  // 展开考点练习
  const openKnowExerciseGroup = (knowTypeCode: string) => {
    // 关闭所有分组
    knowExerciseGroupList.value[swiperCurrent.value].filter(group => group.code != knowTypeCode).forEach(group => group.status = 'close')

    let knowExerciseGroup = knowExerciseGroupList.value[swiperCurrent.value].find(item => item.code === knowTypeCode)
    if (knowExerciseGroup) {
      knowExerciseGroup.status = knowExerciseGroup.status == 'close' ? 'open' : 'close'
    }
  }

  // 计算swiper的高度
  const swiperHeight = computed(() => {

    let knowExerciseGroup = knowExerciseGroupList.value[swiperCurrent.value]
    let length = knowExerciseGroup.length
    let knowLength = 0;
    let knowExerciseGroupItem = knowExerciseGroup.find(item => item.status == 'open')
    if (knowExerciseGroupItem) {
      knowLength = knowExerciseGroupItem.knows?.length || 0
    }
    if (length < 6) {
      length = 6.2
    }
    let height = (length * 80 + knowLength * 45) * 2 + 'rpx'
    return height
  })

  /**
   * 考点练习进度总览
   */
  const knowExerciseProgressOverView = computed(() => {
    //所有考点
    let knowExerciseProgressOver = useKnowExerciseProgressOver(baseType.value!)
    return knowExerciseProgressOver
  })

  /**
   *  到考点进度
   * @param index
   */
  const toKnowExerciseProgress = (index: number) => {
    swiperCurrent.value = index
  }
  // 去考点练习
  const toKnowExercise = (knowTypeCode: string, knowId: number) => {
    uni.navigateTo({
      url: `/pagesExercise/knowDescription/knowDescription?&baseType=${baseType.value}&knowTypeCode=${knowTypeCode}&knowId=${knowId}`
    })
  }

  // 继续练习
  const continueExercise = (knowTypeCode: string, knowId: number) => {
    uni.navigateTo({
      url: `/pagesExercise/answer/answer?exerciseType=${ExerciseTypeEnum.KnowExerciseQuestions}&baseType=${baseType.value}&knowTypeCode=${knowTypeCode}&knowId=${knowId}`
    })
  }
  //退出
  const goBack = () => {
    uni.navigateBack()
  }
</script>

<style lang="scss" scoped>
  .viewport {
    display: flex;
    flex-direction: column;
    height: 100%;
    background-image: linear-gradient(180deg,
        #d0ffe7 0%,
        #f8f8f8 30%,
        #ffffff 100%),
      linear-gradient(180deg,
        #f8f8f8 0%,
        #ffffff 100%);
  }

  .uni-nav-bar {
    .icon-arrow-left {
      font-weight: bold;
    }

    .title {
      align-self: center;
      flex: 1;
      text-align: center;
      font-size: 32rpx;
      font-weight: bold;
    }
  }

  /* #ifdef MP-TOUTIAO */
  // 抖音自定义导航栏
  .toutiao-nav-bar {

    // 顶部占位
    .status-bar {
      width: 100vw;
      height: v-bind(statusBarHeight);
    }

    // 标题行
    .title-container {
      display: flex;
      flex-direction: row;
      align-items: center;
      // justify-content: center;
      height: v-bind(titleHeight);

      .title {
        margin-left: 82rpx;
        font-size: 32rpx;
        // font-weight: bold;
      }
    }
  }

  /* #endif */

  .scroll-view {
    display: flex;
    flex-direction: column;
  }

  // 考点练习进度
  .exercise-progress {
    padding: 0rpx 30rpx;

    .progress-title {
      font-size: 36rpx;
      font-weight: bold;
    }

    .progress-container {
      margin-top: 30rpx;

      .progress-overview {
        padding: 20rpx;
        background-color: #ffffff;
        box-shadow: 7rpx 6rpx 5rpx 0rpx rgba(155, 155, 155, 0.04);
        border-radius: 20rpx;

        .overview-items {
          margin-top: 30rpx;
          display: flex;
          justify-content: space-around;
          align-items: center;

          .item {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;

            .num {
              font-size: 50rpx;
              color: #282529;
              font-weight: bold;
            }

            .desc {
              font-size: 26rpx;
              color: #888888;
            }
          }
        }

        .overview-tips {
          display: flex;
          justify-content: space-between;
          margin-top: 35rpx;
          padding: 20rpx;
          background-color: #f7f8f9;
          border-radius: 10rpx;

          .tips {
            display: flex;
            align-items: center;
            font-size: 22rpx;
            color: #333134;
            line-height: 33rpx;

            .tag {
              margin-right: 20rpx;
              width: 59rpx;
              height: 33rpx;
              font-size: 20rpx;
              color: #dc8815;
              text-align: center;
              background-color: #f9ece5;
              border-radius: 4rpx;
            }
          }

          .btn {
            font-size: 24rpx;
            color: #29c56f;
            font-weight: bold;
          }
        }
      }
    }

  }

  .exercise-progress-header {
    display: flex;
    flex: 1;
    flex-direction: column;
    margin-top: 20rpx;
    background-color: #ffffff;
    border-radius: 20rpx 20rpx 0 0;

  }

  .swiper-container {

    background-color: #ffffff;
    height: v-bind(swiperHeight);

    .know-type-item {
      display: flex;
      flex-direction: column;
      padding: 0rpx 30rpx;

      .know-type-item-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 26rpx 0;
        margin-bottom: 20rpx;

        border-bottom: #f5f5f5 solid 2rpx;

        .know-type-item-label {
          display: flex;
          align-items: center;
          font-size: 30rpx;

          .icon {
            font-size: 40rpx;
            color: #29c56f;


            &.open {
              transform: rotate(180deg);
              // transition: all 1s;
            }

            &.close {
              transform: rotate(0deg);
              // transition: all 1s;
            }
          }

          .name {
            margin-left: 20rpx;
          }
        }

        .know-type-item-num {
          font-size: 24rpx;
          color: #888888;
        }
      }

      .know-item-content {
        .know-item {
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          align-items: center;
          padding: 10rpx 0 10rpx 50rpx;

          .title {
            font-size: 26rpx;
            color: #0f0f0f;
          }

          .tips {
            display: flex;
            justify-content: start;
            padding: 16rpx 0;

            .txt {
              margin-right: 40rpx;
              font-size: 22rpx;
              color: #8e8e8e;

              .num {
                margin-left: 10rpx;
                color: #32ab7c;
              }
            }
          }
        }
      }


    }

    .know-type-empty {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin-top: 30%;
      flex: 1;

      .img {
        width: 240rpx;
      }

      .txt {
        font-size: 26rpx;
        color: #909090;
      }
    }
  }


</style>
